﻿using System;
using Prism.Mvvm;
using Panuon.UI.Silver;
using Prism.Commands;
using Client.Common;
using System.Windows;
using System.Windows.Controls;
using Prism.Regions;
using CommonServiceLocator;
using System.Threading.Tasks;
using Models;
using Client.DAL;
using System.Windows.Media;

namespace Client.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        #region 绑定属性

        public string LoginUser
        {
            get { return $"{Comm.UserInfo.RealName} ({Comm.UserInfo.UserName})"; }
        }

        //右上角在线标志颜色
        private Brush _badgeColor;

        public Brush BadgeColor
        {
            get { return _badgeColor; }
            set { SetProperty(ref _badgeColor, value, "BadgeColor"); }
        }

        //在线标志是否闪烁
        private bool _badgeWave;

        public bool BadgeWave
        {
            get { return _badgeWave; }
            set { SetProperty(ref _badgeWave, value, "BadgeWave"); }
        }

        #endregion 绑定属性

        #region 属性

        private IRegionManager _regionManager;
        private bool canCloseWindow = false;
        private Window _w;
        private Brush _redBrush;
        private Brush _greenBrush;

        #endregion 属性

        #region 命令

        public DelegateCommand RestartCommand { get; private set; }
        public DelegateCommand<TreeViewItem> MenuSelectCommand { get; private set; }
        public DelegateCommand<Window> ExitCommand { get; private set; }
        public DelegateCommand<Window> LoadCommand { get; private set; }
        public DelegateCommand OpenEditPassCommand { get; private set; }

        #endregion 命令

        #region 构造函数

        public MainWindowViewModel(IRegionManager m)
        {
            RestartCommand = new DelegateCommand(RestartApp);
            MenuSelectCommand = new DelegateCommand<TreeViewItem>(MenuSelected);
            LoadCommand = new DelegateCommand<Window>(Load);
            OpenEditPassCommand = new DelegateCommand(OpenEditPass);
            _regionManager = m;
            BrushConverter bc = new BrushConverter();
            _greenBrush = bc.ConvertFromString("#0CFF00") as Brush;
            _redBrush = bc.ConvertFromString("#FF0000") as Brush;
            BadgeColor = _greenBrush;
            Task.Run(HeartBeat);
        }

        #endregion 构造函数

        #region 方法

        private async void HeartBeat()
        {
            int failCount = 0;
            while (Comm.Running)
            {
                if (Comm.UserInfo is null)
                {
                    System.Threading.Thread.Sleep(10000);
                    continue;
                }
                try
                {
                    StateModel hbState = new StateModel { CurStep = Steps.Send };
                    void callback(RetModel rm)
                    {
                        if (hbState.CurStep != Steps.Send) return;
                        hbState.RM = rm;
                        hbState.CurStep = rm.Success ? Steps.Succ : Steps.Fail;
                    }
                    UserSrv.HeartBeat(callback);
                    await hbState.CheckState(10);
                    if (hbState.CurStep != Steps.Succ)
                    {
                        failCount++;
                        BadgeColor = _redBrush;
                        BadgeWave = true;
                        if (failCount > 5)
                        {
                            ShowDisconnect("当前连接中断，请重新登录");
                            return;
                        }
                    }
                    else
                    {
                        BadgeColor = _greenBrush;
                        BadgeWave = false;
                        failCount = 0;
                    }
                }
                catch (Exception)
                {
                }
                System.Threading.Thread.Sleep(10000);
            }
        }

        private void ShowDisconnect(string err)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Comm.ShowErr(err, "连接检测");
                RestartApp();
            });
        }

        //打开修改密码
        private void OpenEditPass()
        {
            var w = new Views.EditPassView()
            {
                Owner = Comm.Shell
            };
            w.ShowDialog();
        }

        //窗口载入
        private void Load(Window w)
        {
            _w = w;
            w.Closing += (sender, e) =>
                {
                    if (canCloseWindow)
                        return;
                    AnimationHelper.SetDurationSeconds(_w, 0.5);
                    AnimationHelper.SetBeginTimeSeconds(_w, 0);
                    AnimationHelper.SetFadeOut(_w, true);
                    AnimationHelper.AddCompletedHandler(
                        _w,
                        (s, se) => { canCloseWindow = true; w.Close(); });
                    e.Cancel = true;
                    canCloseWindow = true;
                };
        }

        //重启程序
        private void RestartApp()
        {
            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
            _w.Close();
        }

        //菜单选择
        private void MenuSelected(TreeViewItem t)
        {
            if (t.Tag != null)
            {
                GC.Collect();
                _regionManager.RequestNavigate("MainContent", t.Tag.ToString());
            }
        }

        #endregion 方法
    }
}